import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const Login = () => import('@/views/login')
const Home = () => import('@/views/home')
const Publish = () => import('@/views/publish')
const Article = () => import('@/views/article')
const Layout = () => import('@/views/layout')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    // 通过children进行路由嵌套
    children: [
      {
        path: '/home',
        alias: '/', // 别名
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 路由前置守卫
// 通过判断token是否存在  控制其在登录页和首页的跳转
router.beforeEach((to, from, next) => {
  Nprogress.start()
  // 假如有token
  if (getItem()) {
    // 假如跳转到首页,不让他跳转,而是跳转到首页,否则正常跳转
    // toLowerCase() 强制转换为小写
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
    // 如果没有token
  } else {
    // 假如要跳转到首页 正常跳转  否则  直接跳到首页
    if (to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})
// 路由后置守卫
router.afterEach((to, form) => {
  Nprogress.done()
  // console.log(to, form)
})

// 解决路由小缺陷  路由跳转时可能会报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
